<?php

	namespace app\index\controller\ohcard;

	use app\common\controller\Frontend;
	use app\common\model\ohcard\Ohcard;
	use app\common\model\ohcard\OhcardIdentify;
	use app\index\validate\ohcard\Identify as IdentifyValidate;

	class Identify extends Frontend{
    	protected $layout = 'default';
		protected $noNeedRight = '*';
		protected $model = null, $ohcardModel = null;

		public function _initialize(){
			parent::_initialize();

			$this->model = new OhcardIdentify();
			$this->ohcardModel = new Ohcard();

			$this->view->assign('title', __('360°识人'));
		}

		public function index(){
			$where = ['user_id' => $this->auth->id];
			$list = $this->model->where($where)->order('id desc')->paginate(10);
			$this->view->assign('list', $list);

			return $this->view->fetch();
		}

		public function create(){
			$balance = \app\common\model\goods\record\Ohcard::getBalance($this->auth->id);
			if($balance <= time()){
				return $this->error('请先开通欧卡功能',url('goods/index'));
			}

			if($this->request->isPost()){
				$datas = $this->request->post();
				$data = [
					'user_id' => $this->auth->id,
					'title' => $datas['title'],
					'room_code' => date('YmdHis'.rand(1000,9999)),
					'is_adult' => $datas['is_adult'],
				];
				$room = $this->model->validate(IdentifyValidate::class)->save($data);
				if($room === false) return $this->error($this->model->getError());
				$room_id = $this->model->id;
				return $this->success('创建成功',url('ohcard.identify/room',['id' => $room_id]),['room_id' => $room_id]);
			}

			return $this->view->fetch();
		}

		public function room($id){
			$this->assignconfig('room_id', $id);
			return $this->view->fetch();
		}

		public function info($room_id){
			$room = $this->model->where(['id' =>$room_id, 'user_id' => $this->auth->id])->find();
			if(!$room){
				return $this->error('房间不存在',url('ohcard.identify/index',[],false,true));
			}else{
				return $this->success('','',$room);
			}
		}

		public function close($room_id){
			$res = $this->model->update(['status'=>0],['id' => $room_id]);
			if($res){
				return $this->success('关闭成功');
			}else{
				return $this->error('关闭失败');
			}
		}

		public function selectCard($id, $selected){
			$res = $this->model->update(['choose_id' => implode(',',$selected)],['id' => $id]);
			return $this->success('','',$res);
		}

		public function setStep($id, $step){
			$res = $this->model->update(['step' => $step],['id' => $id]);
			return $this->success('','',$res);
		}

		public function setSort($id, $sort){
			$res = $this->model->update(['cards_id' => htmlspecialchars_decode($sort)],['id' => $id]);
			return $this->success('','',$res);
		}

		public function setAnalysis($id, $analysis){
			$res = $this->model->update(['analysis' => $analysis],['id' => $id]);
			return $this->success('','',$res);
		}
	}